package bold.deposit;

import bold.deposit.interception.NoAuthorize;
import bold.deposit.interception.argument.Ask;
import bold.deposit.mybatis.mapper.UserMapper;
import bold.deposit.mybatis.model.User;
import bold.deposit.useful.Request;
import bold.deposit.useful.RequestUtil;
import bold.deposit.useful.Result;
import bold.deposit.useful.valid.$Valid;
import bold.storage.component.BaseDao;
import bold.storage.component.Where;
import bold.storage.core.DB;
import bold.storage.core.Page;
import bold.storage.core.Record;
import bold.storage.core.RecordList;
import bold.storage.util.DateUtil;
import bold.storage.util.FilterUtil;
import bold.storage.util.ID;
import lombok.Cleanup;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Map;

@Log4j2
@RestController
@RequestMapping("table")
@NoAuthorize
public class TableController extends BaseDao {

    @Autowired
    public UserMapper userMapper;
    @Autowired
    private TableService tableService;

    @Value("#{prop.key2}")
    private String key1;

    @PostMapping("loginInfo")
    public Result loginInfo(Account account) {
        return new Result(account);
    }

    @PostMapping("save")
    public Result save(HttpServletRequest request) throws SQLException {
        Map<String, String> params = RequestUtil.getMap(request);
        params.put("id", ID.instance.get());
        params.put("add_time", DateUtil.getTime());
        return new Result(model("table", params).insert());
    }

    @PostMapping("delete")
    public Result delete(String id) throws SQLException {
        return new Result(model("table").deleteByPk(id));
    }

    @RequestMapping("update")
    public Result update(HttpServletRequest request) throws SQLException {
        Map<String, String> params = RequestUtil.getAllMap(request);
        Map<String, String> newMap = FilterUtil.filter(params, "table");
        return new Result(model("table", newMap).updateByPk());
    }

    @RequestMapping(value = "get")
    public Result get(String id) throws SQLException {
        Record record = query("table").where("id", id).record();
        return new Result(record);
    }

    /**
     * @param file 注意 这的参数名为上传古来的
     */
    @RequestMapping("upload")
    public Result upload(MultipartFile file) throws IOException, SQLException {
        if (file == null || file.isEmpty()) {
            return Result.Empty;
        }
        InputStream inputStream = file.getInputStream();
        boolean boo = model("account").set("photo", inputStream).updateByPk("1");
        return new Result(boo);
    }

    @RequestMapping("photo")
    public void photo(HttpServletResponse response) throws SQLException, IOException {
        Record record = query("account").select("photo").where("id", "1").record();
        @Cleanup
        ByteArrayInputStream inputStream = new ByteArrayInputStream((byte[]) record.get("photo"));
        // 7.设置响应头，控制浏览器不要缓存
        response.setContentType("image/jpeg");
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        // 8.将图片写给浏览器
        BufferedImage bufferedImage = ImageIO.read(inputStream);
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }

    @PostMapping("page")
    public Result page(Request request) throws SQLException {
        Map<String, String> params = request.getPrams();
        Where where = where().like("name", params.get("name")).like("content", params.get("content"));
        Page page = query("table").where(where).orderAsc("id")
                .paginate(params.get("pageIndex"), params.get("pageSize"));
        return new Result(page);
    }

    @RequestMapping("list")
    public RecordList list() throws SQLException {
        return query("table").recordList();
    }

    @RequestMapping("cache")
    public Object cache(String id) {
        $Valid.isAnyBlank(id);
        return new Result(tableService.cache(id));
    }

    @RequestMapping("param")
    //spring这个傻狗 自定义的顺序不能改所以用不了 map类型
    public Object param(@Ask(all = true) Request request, Account account) {
        Map<String, String> map = request.getPrams();
        map.put("id", "123");
        return map.toString();
    }

    /**
     * 当当网 分表
     */
    @RequestMapping("userSubTable")
    public Object userSubTable() {
        for (int i = 1; i <= 2; i++) {
            User user = new User();
            user.setId((long) i);
            user.setAge(i);
            user.setName("name" + i);
            boolean save = userMapper.save(user);
            System.out.println("分表结果" + save);
        }
        return "doSuccess";
    }
}
